package net.zzy.pbbot.plugin.tiktok.api;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import net.lz1998.pbbot.bot.Bot;
import net.lz1998.pbbot.bot.BotPlugin;
import net.lz1998.pbbot.utils.Msg;
import net.zzy.pbbot.plugin.tiktok.entity.TikTokDaoEntity;
import net.zzy.pbbot.plugin.tiktok.entity.TikTokResp;
import net.zzy.pbbot.plugin.tiktok.mapper.TikTokGirlsMapper;
import net.zzy.pbbot.plugin.tiktok.service.TikTokService;
import net.zzy.pbbot.util.HttpsUtils;
import onebot.OnebotEvent;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static net.zzy.pbbot.finalfield.Api.TIK_TOK_GET;
import static net.zzy.pbbot.finalfield.Command.TIK_TOK;

/**
 * @author zhuZhaoYang
 * @date 2021/9/25 22:33
 */
@Component
public class TikTok extends BotPlugin {

    private TikTokService tikTokService;

    @Autowired
    public void setTikTokService(TikTokService tikTokService) {
        this.tikTokService = tikTokService;
    }

    private TikTokGirlsMapper tikTokGirlsMapper;

    @Autowired
    public void setTikTokGirlsMapper(TikTokGirlsMapper tikTokGirlsMapper) {
        this.tikTokGirlsMapper = tikTokGirlsMapper;
    }

    @SneakyThrows
    @Override
    public int onPrivateMessage(@NotNull Bot bot, @NotNull OnebotEvent.PrivateMessageEvent event) {
        String rawMessage = event.getRawMessage();
        if (!rawMessage.startsWith(TIK_TOK)) {
            return MESSAGE_IGNORE;
        }
        Msg msg = getMsg();
        msg.sendToFriend(bot, event.getUserId());
        return MESSAGE_BLOCK;
    }

    @SneakyThrows
    @Override
    public int onGroupMessage(@NotNull Bot bot, @NotNull OnebotEvent.GroupMessageEvent event) {
        String rawMessage = event.getRawMessage();
        if (!rawMessage.startsWith(TIK_TOK)) {
            return MESSAGE_IGNORE;
        }
        Msg msg = getMsg();
        msg.sendToGroup(bot, event.getGroupId());
        return MESSAGE_BLOCK;
    }

    public Msg getMsg() throws Exception {
        TikTokDaoEntity tikTokDaoEntity = tikTokService.getTikTokUrl();
        Msg msg = Msg.builder();
        if (tikTokDaoEntity == null) {
            msg.text("获取视频失败");
            return msg;
        }
        if (tikTokDaoEntity.getMp4() == null) {
            String get = HttpsUtils.get(TIK_TOK_GET + tikTokDaoEntity.getUrl(), null, null);
            TikTokResp tikTokResp = JSON.parseObject(get, TikTokResp.class);
            if (!"success".equals(tikTokResp.getStatus())) {
                msg.text("获取视频失败");
                return msg;
            }
            tikTokDaoEntity.setMp4(tikTokResp.getMp4());
            tikTokDaoEntity.setDesc(tikTokResp.getDesc());
            tikTokGirlsMapper.updateById(tikTokDaoEntity);
        }
        msg.video(tikTokDaoEntity.getMp4(), tikTokDaoEntity.getMp4(), true);
        return msg;
    }
}
